package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    ObjectMapper objectMapper = new ObjectMapper();

    public void set(String key, Object object, Long time, TimeUnit unit) throws JsonProcessingException {
        stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(object), time, unit);
    }

    public void setWithLogicExpices(String key, Object object, Long time) throws JsonProcessingException {
        RedisData redisData = new RedisData();
        redisData.setData(object);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(redisData));
    }


    //    雪崩
    public <R, ID> R queryWithPassThrough(String head, ID id, Class<R> type, Function<ID, R> dback, Long time, TimeUnit unit) throws JsonProcessingException {
        String key = head + id;
        String shopJSon = stringRedisTemplate.opsForValue().get(key);

        objectMapper.registerModule(new JavaTimeModule());

        if ("".equals(shopJSon)) {
//            redis有数据。命中空字符。
            throw new HmdpException(ResultCodeEnum.shop_Not);
        }

        if (StringUtils.isNotBlank(shopJSon)) {
//            redis有数据。命中
            R r = objectMapper.readValue(shopJSon, type);
            return r;
        }

        R r = dback.apply(id);

        if (r == null) {
//            穿透了.
            stringRedisTemplate.opsForValue().set(key, "", 20, TimeUnit.SECONDS);
            throw new HmdpException(ResultCodeEnum.shop_Not);
        }

        String shopString = objectMapper.writeValueAsString(r);
        stringRedisTemplate.opsForValue().set(key, shopString);
        stringRedisTemplate.expire(RedisConstant.Shop_store + id, time, unit);
        return r;
    }


    public boolean tryLock(String id) {
//如果有锁。
        boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(id, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    public void unLock(String id) {
        stringRedisTemplate.delete(id);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //    逻辑过期
    public <R, ID> R queryWithLogicExpire(String keyPredfix, ID id, Class<R> type, Function<ID, R> dback) throws JsonProcessingException {

        String shopJSon = stringRedisTemplate.opsForValue().get(keyPredfix + id);
// 注册 JavaTimeModule 以支持 LocalDateTime 反序列化
        objectMapper.registerModule(new JavaTimeModule());

        if ("".equals(shopJSon) || StringUtils.isBlank(shopJSon)) {
//            redis有无效数据。命中空字符。
            throw new HmdpException(ResultCodeEnum.shop_Not);
        }


        RedisData redisData = objectMapper.readValue(shopJSon, RedisData.class);
// 反序列化 redisData 对象的 data 部分为 Shop 类
        R redisData_shop = objectMapper.convertValue(redisData.getData(), type);

//4.        redis命中后判断是否不为空。而且判断时间是否过期，

        // 转换为时间戳（秒数）

        if (redisData.getExpireTime().isAfter(LocalDateTime.now()) && StringUtils.isNotBlank(shopJSon)) {
//没有过期
            return redisData_shop;
        }
//        过期了
        String lockKey = RedisConstant.CACHE_Shop_Lock + id;
        boolean b = tryLock(lockKey);
        if (!b) {
            return redisData_shop;
        }
//锁上了。
        CACHE_REBUILD_EXECUTOR.submit(() -> {
            try {
                saveShop2Redis(id, 60 * 60L, dback);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            } finally {
                this.unLock(lockKey);
            }
        });

        return redisData_shop;
    }

    public <R, ID> void saveShop2Redis(ID id, long expireSeconds, Function<ID, R> dback) throws JsonProcessingException {
        R shop = dback.apply(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(RedisConstant.Shop_store + id, "", 20, TimeUnit.MINUTES);
        }
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        String s = objectMapper.writeValueAsString(redisData);
        stringRedisTemplate.opsForValue().set(RedisConstant.Shop_store + id, s);
    }
}
